package bjtu.tjj.simpledy.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class ControllerAspect {
    @Pointcut("execution(public * bjtu.tjj.simpledy.controller.*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object logging(ProceedingJoinPoint joinPoint) throws Throwable {

        //开始执行时间
        long startTime = System.currentTimeMillis();
        //提取类名
        String className = joinPoint.getTarget().getClass().getSimpleName();
        //提取方法名
        String methodsName = joinPoint.getSignature().getName();
        // 提取方法参数（输入参数）
        Object[] methodArgs = joinPoint.getArgs();
        Object result = null;
        Throwable throwable = null;
        //执行结果
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            throwable = e;
        }
        //执行结束时间
        long endTime = System.currentTimeMillis();
        //方法执行时间
        long executionTime = endTime - startTime;
        // 记录日志
        log.info("执行方法%s.%s 参数：%s 执行时间：%sms "
                .formatted(className, methodsName, Arrays.toString(methodArgs), executionTime) +
                (throwable == null ?
                        "返回结果：%s".formatted(result) :
                        "出现异常：%s".formatted(throwable)
                ));
        if (throwable != null) {
            throw throwable;
        }
        return result;
    }
}
